package utils

import (
	"errors"
	"fmt"
	"math/rand"
	"time"
)

// 计算两个时间段之前的时间切片
func GetTimeSliceForDay(s, e string) (timeSlice []string, err error) {
	sTime, err := time.ParseInLocation("2006-01-02", s, time.Local)
	if err != nil {
		return nil, err
	}
	eTime, err := time.ParseInLocation("2006-01-02", e, time.Local)
	if err != nil {
		return nil, err
	}

	for {

		if sTime.After(eTime) {
			//时间超过
			//fmt.Println("时间超过")
			break
		}

		timeSlice = append(timeSlice, sTime.Format("2006-01-02"))
		sTime = sTime.AddDate(0, 0, 1)

	}
	return timeSlice, err
}

func GetTimeSliceForMonth(s, e string) (timeSlice []string, err error) {
	// 输入校验
	startTime, err := time.ParseInLocation("2006-01-02", s, time.Local)
	if err != nil {
		return nil, err
	}

	endTime, err := time.ParseInLocation("2006-01-02", e, time.Local)
	if err != nil {
		return nil, err
	}

	if startTime.After(endTime) {
		return nil, errors.New("start time must be earlier than end time")
	}

	// 计算跨度月数
	month := endTime.Month() - startTime.Month()
	year := (endTime.Year() - startTime.Year()) * 12
	monthDiff := int(month) + year

	// 生成时间片段
	var slices []string
	for i := 0; i <= monthDiff; i++ {
		slice := startTime.AddDate(0, i, 0).Format("200601")
		slices = append(slices, slice)
	}

	return slices, nil

}

// 求出24小时的时间切片
func GetTimeSliceForHour() (timeSlice []string, err error) {
	for i := 0; i < 24; i++ {
		timeSlice = append(timeSlice, fmt.Sprintf("%d", i))
	}
	return timeSlice, err
}

func GetTableNameForRand(tableName string) string {
	rand.Seed(time.Now().UnixNano())
	return fmt.Sprintf("%s_%s_%d", tableName, time.Now().Format("20060102_150405"), rand.Intn(100))
}

func GetTableNameForYou(tableName string, prefix string) string {
	return fmt.Sprintf("%s_%s_%s", tableName, time.Now().Format("20060102_150405"), prefix)
}

// 求出2023-10-19这个月第一天的日期
func GetFirstDateOfMonth(d time.Time) time.Time {
	d = d.AddDate(0, 0, -d.Day()+1)
	return d
}

// 求出2023-10-19这个月最后一天的日期
func GetLastDateOfMonth(d time.Time) time.Time {
	return GetFirstDateOfMonth(d).AddDate(0, 1, -1)
}

// 求出今日零时零分零秒的时间，输出为unix时间戳
func GetZeroTime(d time.Time) time.Time {
	return time.Date(d.Year(), d.Month(), d.Day(), 0, 0, 0, 0, d.Location())
}
